package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序工具组件接口实现类
 *
 * @Author mr.chen
 * @Date 2025/5/23 16:29
 */
@Service
public class WechatServiceImpl implements WechatService {

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 获取用户登录小程序url
     */
    private static final String GET_OPPID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 获取接口调用凭据
     */
    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    private static final String POST_PHONENUMBER_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    private Map<String,Object> getBaseParam(){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",appId);
        paramMap.put("secret",appSecret);
        return paramMap;
    }

    /**
     * 根据临时凭证码（openId获取专用凭证码）获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
       //添加数据
        Map<String, Object> paramMap = this.getBaseParam();
        paramMap.put("js_code",code);
        paramMap.put("grant_type", "authorization_code");
        //使用hutool工具类调用微信小程序登录
        String resultJSON = HttpUtil.get(GET_OPPID_URL,paramMap);
        if(StringUtils.isBlank(resultJSON)){
            throw new BaseException("调用微信小程序登录接口失败");
        }
        //解析数据获取oppid
        JSONObject jsonObject = JSON.parseObject(resultJSON);

        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode!=null && errcode!=0) {
            throw new BaseException("调用微信小程序登录接口失败");
        }
        return  jsonObject.getString("openid");
    }

    /**
     * 获取接口凭证
     * @return
     */
    private String getAccessToken(){
        //1. 准备请求参数
        Map<String,Object> paramMap = getBaseParam();
        paramMap.put("grant_type","client_credential");

        //2. 使用hutool工具发起GET请求微信获取接口调用凭据接口
        String resultJSON = HttpUtil.get(GET_TOKEN_URL, paramMap);

        //3. 解析响应结果，得到access_token接口访问凭证
        if(StringUtils.isBlank(resultJSON)) {
            throw new BaseException("调用获取接口凭证的接口失败");
        }
        JSONObject jsonObject = JSON.parseObject(resultJSON);
        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode!=null && errcode!=0) {
            throw new BaseException("调用获取接口凭证的接口失败");
        }
        return jsonObject.getString("access_token");
    }

    /**
     * 根据临时凭证码（手机号获取专用凭证码，非openId凭证码）获取手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhoneNumber(String code) {
        //获取接口调用凭据
        String accessToken = this.getAccessToken();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code",code);
        String resultJSON = HttpUtil.post(POST_PHONENUMBER_URL+accessToken, JSON.toJSONString(paramMap));
        if(StringUtils.isBlank(resultJSON)){
            throw new BaseException("调用手机号获取专用凭证码接口失败");
        }

        //3. 解析响应结果，得到phoneNumber手机号
        JSONObject jsonObject = JSON.parseObject(resultJSON);
        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode!=null && errcode!=0) {
            throw new BaseException("调用微信获取手机号接口失败");
        }
        String phoneInfoJSON = jsonObject.getString("phone_info");
        JSONObject PhoneObject = JSON.parseObject(phoneInfoJSON);
        return PhoneObject.getString("phoneNumber");
    }
}
